package com.kuaiyin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuaiyin.dto.DepartmentsDTO;
import com.kuaiyin.entity.Departments;
import com.kuaiyin.enums.BizCodeEnum;
import com.kuaiyin.exception.BaseException;
import com.kuaiyin.mapper.DepartmentsMapper;
import com.kuaiyin.service.IDepartmentsService;
import com.kuaiyin.utils.PageHelper;
import com.kuaiyin.utils.PageResult;
import com.kuaiyin.vo.DepartmentsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.function.Consumer;

/**
 * <p>
 * 部门信息表（含完整审计字段） 服务实现类
 * </p>
 *
 * @author ng
 * @since 2025-04-22
 */
@Slf4j
@Service
public class DepartmentsServiceImpl extends ServiceImpl<DepartmentsMapper, Departments> implements IDepartmentsService {
    @Autowired
    private DepartmentsMapper departmentsMapper;

    @Override
    public void saveDepartments(DepartmentsDTO departmentsDTO) {
        if (lambdaQuery().eq(Departments::getName, departmentsDTO.getName()).exists()) {
            throw BaseException.of(BizCodeEnum.DEPARTMENT_NAME_EXISTS);
        }
        Departments entity = new Departments();
        BeanUtils.copyProperties(departmentsDTO, entity);
        departmentsMapper.insert(entity);
    }

    @Override
    public Boolean updateStatus(Integer id, Boolean status) {
        return departmentsMapper.updateStatus(id, status) > 0;
    }

    @Override
    public void removeById(Integer id) {
        Integer sum = departmentsMapper.getUser(id);
        if (sum > 0){
            throw BaseException.of(BizCodeEnum.DEPARTMENT_HAS_USERS_CANNOT_DELETE);
        }
        super.removeById(id);
    }

    @Override
    public PageResult<DepartmentsVO> getDepartments(Integer page, Integer size, Consumer<LambdaQueryWrapper<Departments>> condition) {
        return  PageHelper.queryWithVo(page, size, departmentsMapper, DepartmentsVO.class,condition);
    }

    @Override
    public void updatDepartments(Integer id, DepartmentsDTO departmentsDTO) {
        departmentsDTO.setId(id);
        //校验名称是否已存在
        if (lambdaQuery().eq(Departments::getName, departmentsDTO.getName()).ne(Departments::getId, id).exists()) {
            throw BaseException.of(BizCodeEnum.DEPARTMENT_NAME_EXISTS);
        }
        Departments entity = new Departments();
        BeanUtils.copyProperties(departmentsDTO, entity);
        departmentsMapper.updateById(entity);
    }
}
